#!/usr/bin/make -f
SHELL := sh -e
SOURCE := $(shell dpkg-parsechangelog -SSource)
VERSION := $(shell dpkg-parsechangelog -SVersion)
VERSION_UPSTREAM := $(shell echo "$(VERSION)" | sed -e 's,-[^-]*$$,,')

CONTROL_FILES += debian/bin/gencontrol.py debian/config/defines $(wildcard debian/config/*/defines) $(wildcard debian/config/*/copyright) $(wildcard debian/config/*/LICENSE*)

include debian/rules.defs

GENCONTROL = debian/bin/gencontrol.py

__BINNMU := $(shell dpkg-parsechangelog | sed -rne 's,^Version: .*\+b([0-9]+)$$,\1,p')

build: debian/control
	rm ti-connectivity/wl1271-nvs.bin
	rm ti-connectivity/wl127x-nvs.bin
	rm ti-connectivity/wl12xx-nvs.bin
	cp -v debian/wl1271-nvs.bin ti-connectivity/wl1271-nvs.bin
	cp -v debian/wl1271-nvs.bin ti-connectivity/wl127x-nvs.bin
	cp -v debian/wl1271-nvs.bin ti-connectivity/wl12xx-nvs.bin

clean: debian/control
	dh_testdir
	rm -rf debian/lib/python/__pycache__
	dh_clean

binary-indep:
	dh_testdir
	$(MAKE) -f debian/rules.gen binary-indep

binary-arch:

binary:	binary-indep binary-arch

debian/control debian/rules.gen: $(GENCONTROL) $(CONTROL_FILES)
ifeq ($(wildcard debian/control.md5sum),)
	$(MAKE) -f debian/rules debian/control-real
else ifeq ($(__BINNMU),)
	md5sum --check debian/control.md5sum --status || \
		$(MAKE) -f debian/rules debian/control-real
else
	grep -v debian/changelog debian/control.md5sum | md5sum --check - --status || \
		$(MAKE) -f debian/rules debian/control-real
endif

debian/control-real: $(GENCONTROL) $(CONTROL_FILES)
	$(GENCONTROL) /usr/src/linux-support-$(KERNELVERSION)
	md5sum $^ > debian/control.md5sum
	@echo
	@echo This target is made to fail intentionally, to make sure
	@echo that it is NEVER run during the automated build. Please
	@echo ignore the following error, the debian/control file has
	@echo been generated SUCCESSFULLY.
	@echo
	exit 1

DIR_ORIG = ../orig/$(SOURCE)-$(VERSION_UPSTREAM)
TAR_ORIG_NAME = $(SOURCE)_$(VERSION_UPSTREAM).orig.tar.xz
TAR_ORIG = $(firstword $(wildcard ../$(TAR_ORIG_NAME)) $(wildcard ../orig/$(TAR_ORIG_NAME)))

orig: $(DIR_ORIG)
	rsync --delete --exclude /debian --exclude /.git --link-dest=$(DIR_ORIG)/ -a $(DIR_ORIG)/ .
	QUILT_PATCHES='$(CURDIR)/debian/patches' QUILT_PC=.pc quilt push --quiltrc - -a -q --fuzz=0

$(DIR_ORIG):
ifeq ($(TAR_ORIG),)
	$(error Cannot find orig tarball $(TAR_ORIG_NAME))
else
	mkdir -p ../orig
	tar -C ../orig -xaf $(TAR_ORIG)
endif

maintainerclean:
	-rm debian/control debian/control.md5sum debian/rules.gen
	rm -f debian/*.bug-presubj
	-rm debian/*.copyright
	-rm debian/*.hook.*
	rm -f debian/*.metainfo.xml
	-rm debian/*.preinst
	-rm debian/*.postinst
	-rm debian/*.templates

.PHONY: clean build binary-indep binary-arch binary
